const Joi = require('joi')
const { ParameterError } = require('../errors/application-error')

module.exports = function (schema) {
  return async (ctx, next) => {
    try {
      const base = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(ctx.method)  ? ctx.request.body : ctx.query
      const object = {...(base || {}), ...ctx.params }
      const result = await Joi.object(schema).messages({
        'string.required': '{{#label}} 不能为空',
        'string.empty': '{{#label}} 不能为空',
      }).validateAsync(object) // 防止空时报错
      ctx.state.compiled = result
    } catch (error) {
      // 未定义错误信息时，Joi抛出内置错误提示
      throw new ParameterError(error.message)
    }
    await next()
  }
}
